package com.ecloud.gardenscenter.mqtt.config;

import com.ecloud.gardenscenter.mqtt.MqttClientFactory;
import com.ecloud.gardenscenter.mqtt.MqttMessageFactory;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Squbi
 */
@Configuration
public class MqttBeanConfiguration {
    private final MqttConfiguration mqttConfig;
    private final MqttMessageConfiguration messageConfig;

    public MqttBeanConfiguration(MqttConfiguration mqttConfig, MqttMessageConfiguration messageConfig) {
        this.mqttConfig = mqttConfig;
        this.messageConfig = messageConfig;
    }

    @Bean
    public MqttClientFactory clientFactory() {
        MqttConnectionOptions options = new MqttConnectionOptions();
        options.setAutomaticReconnect(mqttConfig.getAutoReconnect());
        options.setCleanStart(mqttConfig.getCleanStart());
        options.setConnectionTimeout(mqttConfig.getConnectionTimeout());
        return new MqttClientFactory(mqttConfig.getServerUri(), options);
    }

    @Bean
    public MqttMessageFactory messageFactory() {
        MqttMessageFactory messageFactory = new MqttMessageFactory();
        messageFactory.setDuplicate(messageConfig.getDuplicate());
        messageFactory.setMutable(messageConfig.getMutable());
        messageFactory.setRetained(messageConfig.getRetained());
        messageFactory.setQos(messageConfig.getQos());
        return messageFactory;
    }
}
